﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using MiniWeb.Core.Dtos;
using MiniWeb.Web.Controllers.Admin.LinksManager.ViewModels;
using WFramework.MvcPager;
using WFramework.ORM;
using MiniWeb.Task;
using MiniWeb.Core.Entities;

namespace MiniWeb.Web.Controllers.Admin.LinksManager
{
    public class LinksManagerController : BaseController
    {
        private readonly LinksTask _linksTask = new LinksTask();
        public ActionResult List(int? id,string linkName, int pageIndex=1, int pageSize=20)
        {
            var pageList = _linksTask.GetPagedList(id, linkName, pageIndex, pageSize);
            var model = new PagedList<Links>(pageList, pageIndex, pageSize);
            return View(model);
        }

        public ActionResult Save(int? id)
        {
            var model = new SaveLinks();
            if (id != null)
            {
                var item = _linksTask.GetById((int)id);
                model.ID = id;
                model.linkAddress = item.linkAddress;
                model.linkName = item.linkName;

            }
            return View(model);
        }

        [ValidateInput(false)]
        [HttpPost]
        public ActionResult Save(SaveLinks m)
        {
            var item = _linksTask.GetByName(m.linkName);

                if (ModelState.IsValid)
                {
                    if (m.ID == null)
                    {
                        if (item == null)
                        {
                            var model = new Links
                            {
                                linkName = m.linkName,
                                linkAddress = m.linkAddress
                            };
                            _linksTask.Add(model);
                        }
                        else
                        {
                            return AlertMsg("链接已存在", HttpContext.Request.UrlReferrer.PathAndQuery);
                        }

                    }
                    else
                    {
                        var model = _linksTask.GetById((int)m.ID);
                        if (model == null)
                        {
                            return AlertMsg("参数错误", HttpContext.Request.UrlReferrer.PathAndQuery);
                        }
                        model.linkName = m.linkName;
                        model.linkAddress = m.linkAddress;
                        _linksTask.UpData(model);
                    }
                    return AlertMsg("保存成功", HttpContext.Request.UrlReferrer.PathAndQuery);

                }

            
            return View();
        }

        [HttpPost]
        public void Delete(int id) 
        {
            _linksTask.Delete(id);
        }

    }
}
